package edu.qhst.chat.netty;

import edu.qhst.chat.netty.cmdhandler.CmdHandlerFactory;
import edu.qhst.chat.netty.cmdhandler.ICmdHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 主消息处理器
 */
public class MainMsgProcessor {

    static private final Logger log = LoggerFactory.getLogger(MainMsgProcessor.class);

    /**
     * 单例对象
     */
    static private final MainMsgProcessor _instance = new MainMsgProcessor();

    /**
     * 私有化类默认构造器
     */
    private MainMsgProcessor() {
    }

    /**
     * 获取单例对象
     *
     * @return 单例对象
     */
    static public MainMsgProcessor getInstance() {
        return _instance;
    }

    private final ExecutorService es = Executors.newSingleThreadExecutor((newRunable) -> {
        Thread thread = new Thread(newRunable);
        thread.setName("MainMsgProcessor");
        return thread;
    });

    /**
     * 处理客户端消息
     */
    public void process(ChannelHandlerContext ctx, Object msg) {
        if (null == ctx ||
                null == msg) {
            return;
        }

        // TODO 获取命令
        Integer code = 0;

        log.info(
                "收到客户端消息, code = {}",
                code
        );

        es.submit(() -> {
            ICmdHandler cmdHandler = CmdHandlerFactory.create(code);
            if (cmdHandler == null) {
                log.error(
                        "未找到相对应的指令处理器, code = {}",
                        code
                );
                return;
            }

            try {
                cmdHandler.handle(ctx, msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 处理消息对象
     *
     * @param r Runnable
     */
    public void process(Runnable r) {
        if (null != r) {
            es.submit(r);
        }
    }

}
